<?php
include(WEIXIN_ROBOT_PLUGIN_DIR.'admin/includes/class-weixin-user.php');
include(WEIXIN_ROBOT_PLUGIN_DIR.'admin/includes/class-weixin-user-tag.php');
include(WEIXIN_ROBOT_PLUGIN_DIR.'admin/includes/class-weixin-message.php');
include(WEIXIN_ROBOT_PLUGIN_DIR.'admin/includes/class-weixin-reply-setting.php');
include(WEIXIN_ROBOT_PLUGIN_DIR.'admin/includes/class-weixin-qrcode.php');

add_filter('wpjam_weixin_users_list_table', function(){
	$style = '
	th.column-openid{width:224px;}
	th.column-username{width:200px;}
	th.column-sex{width:28px;}
	th.column-country{width:56px;}
	th.column-province{width:70px;}
	th.column-province{width:56px;}
	th.column-credit{width:62px;}
	th.column-subscribe_time,th.column-unsubscribe_time{width:98px;}
	';

	return [
		'title'				=> '微信用户',
		'singular'			=> 'weixin-user',
		'plural'			=> 'weixin-users',
		'primary_column'	=> 'username',
		'primary_key'		=> 'openid',
		'model'				=> 'WEIXIN_AdminUser',
		'ajax'				=> true,
		'style'				=> $style
	];
});

add_filter('wpjam_weixin_user_tags_list_table', function(){
	return [
		'title'				=> '用户标签',
		'singular'			=> 'weixin-user-tag',
		'plural'			=> 'weixin-user-tags',
		'primary_column'	=> 'name',
		'primary_key'		=> 'id',
		'model'				=> 'WEIXIN_UserTag',
		'ajax'				=> true,
	];
});

function wpjam_weixin_users_ajax_response(){
	$action	= $_POST['page_action'];
	$data	= wp_parse_args($_POST['data']);

	if($action == 'submit'){
		$type			= $data['type']??'';

		if($type == 'list'){
			$next_openid	= $data['next_openid']??'';

			if($next_openid == ''){
				WEIXIN_User::Query()->update(array('subscribe'=>0));	// 第一次抓取将所有的用户设置为未订阅
			}

			$response = weixin()->get_user_list($next_openid);

			if(is_wp_error($response)){
				wpjam_send_json($response);
			}

			$next_openid	= $response['next_openid'];
			$count			= $response['count'];

			if($count){
				$datas	= array_map(function($openid){return array('openid'=>$openid, 'subscribe'=>1); }, $response['data']['openid']);

				WEIXIN_User::insert_multi($datas);
			}

			if($next_openid && $count > 0){
				wpjam_send_json(['errcode'=>0, 'type'=>'list', 'next_openid'=>$next_openid, 'errmsg'=>'同步列表中，请勿关闭浏览器。下一组：'.$next_openid]);
			}else{
				wpjam_send_json(['errcode'=>0, 'type'=>'batch', 'errmsg'=>'开始同步用户信息，请勿关闭浏览器。']);
			}
		}else{
			$openids	= WEIXIN_User::Query()->where('subscribe',1)->where_lt('last_update', (time()-MONTH_IN_SECONDS*6))->limit(100)->get_col('openid');

			if($openids){
				$result = WEIXIN_User::batch_get_user_info($openids, true);
				if(is_wp_error($result)){
					wpjam_send_json($response);
				}

				if(count($openids) > 90){	// 如果有大量的用户，就再抓一次咯
					wpjam_send_json(['errcode'=>0, 'type'=>'batch', 'errmsg'=>'同步用户信息中，请勿关闭浏览器。下一组：'.current($openids)]);
				}else{
					wpjam_send_json(['errcode'=>0]);
				}
			}else{
				wpjam_send_json(['errcode'=>0]);
			}
		}
	}
}

function weixin_sync_users_page(){
	global $current_admin_url;
	// $users_sync = get_option('weixin_'.weixin_get_appid().'_users_sync');

	?>
	<h2>同步用户</h2>
	
	<p>从微信获取订阅用户列表，同步到本地数据库。</p>
	
	<?php 

	$fields	= [
		'type'			=> ['title'=>'',	'type'=>'hidden',	'value'=>'list'],
		'next_openid'	=> ['title'=>'',	'type'=>'hidden',	'value'=>''],
	];

	wpjam_ajax_form([
		'fields'		=> $fields, 
		'action'		=> 'submit', 
		'submit_text'	=> '同步'
	]);
	?>

	<script type="text/javascript">
	jQuery(function($){
		$('body').on('page_action_success', function(e, response){
			var action	= response.page_action;

			if(action == 'submit'){
				if(response.errmsg){
					$('#next_openid').val(response.next_openid);
					$('#type').val(response.type);

					setTimeout(function(){
						$('#wpjam_form').submit();
					}, 400);
				}else{
					$('#next_openid').val('');
				}		
			}
		});
	});
	</script>
	<?php

	// if(isset($_GET['action'])){
	// 	update_option('weixin_'.weixin_get_appid().'_users_sync', 'syncing');
		
	// 	if(!wpjam_is_scheduled_event('weixin_get_user_list')){	
	// 		wp_schedule_single_event(time()+3, 'weixin_get_user_list');
	// 	}

	// 	echo '<p>开始同步，请稍后！</p>';
	// }else{
	// 	if($users_sync == 'syncing'){
	// 		echo '<p>系统正在同步，请稍后！</p>';
	// 	}else{
	// 		if($users_sync){
	// 			echo '<p>上次同步是在'.wpjam_human_time_diff($users_sync).'</p>';
	// 			echo '<p>从微信服务器同步订阅用户到本地服务器所需要时间和公众号的粉丝数有关！</p>';
	// 		}

	// 		echo '<p><a class="button-primary" href="'.$current_admin_url.'&action=1">开始同步</a></p>';
	// 	}
	// }
}